
import config from 'config.js';
import Api from 'api.js';
// 图片
var chooseImage = (app, t, count) =>{
    wx.chooseImage({
        count: count,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // console.log("chooseImage-res:"+JSON.stringify(res));
          // var ImagePaths = t.data.ImagePaths;
          // console.log("ImagePaths:" + JSON.stringify(res.tempFilePaths))
          // ImagePaths = ImagePaths.concat(res.tempFilePaths);
          // console.log("ImagePaths:" + JSON.stringify(ImagePaths))
          // t.setData({
          //   ImagePaths: ImagePaths
          // });
          // 上传后台
          uploadFiles(app, t, res.tempFilePaths, count,1);
        },
    });
}
// 视频
var chooseVideo = (app, t,count) => {
    wx.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        compressed:true,
        camera: 'back',
        success: function (res) {
          // console.log("chooseVideo-res:" + JSON.stringify(res));
          // var Videos = t.data.Videos;
          // console.log("ImagePaths:" + JSON.stringify(res.tempFilePath))
          // Videos.push(res.tempFilePath);
          // console.log("Videos:" + JSON.stringify(Videos))
          // t.setData({
          //   Videos: Videos
          // });
          // 上传后台
          uploadFiles(app, t, res.tempFilePath, count,2);
        }
    })
}

// 录音
var chooseRecord = (app, t, count) => {
  const recorderManager = wx.getRecorderManager();
  // 录音入参
  const options = {
    duration: 10000,
    sampleRate: 44100,
    numberOfChannels: 1,
    encodeBitRate: 192000,
    format: 'aac',
    frameSize: 50
  }
  // 开始录音
  recorderManager.start(options);
// 停止录音之后，把录取到的音频放在res.tempFilePath
  recorderManager.onStop(function (res) {
    var Records = t.data.Records;
    Records.push(res.tempFilePath);
    t.setData({
      Records: Records
    })
  });
}

var uploadFiles = (app, t, tempFilePaths, count,sign) => {
  var that = this;
  // 上传服务器
  //启动上传等待中...  
  wx.showToast({
    title: '正在上传...',
    icon: 'loading',
    mask: true,
    duration: 10000
  });

  Api.Authorization().then(data => {
    var uploadImgCount = 0;
    var filePath = '';
    if (sign == 1) {
      filePath = tempFilePaths[0];
    } else {
      filePath = tempFilePaths
    }
    wx.uploadFile({
      url: config.UploadFile,
      filePath: filePath,
      name: 'Uploadfile_File',
      formData: {
        'MemberID': wx.getStorageSync("MemberID"),
        'WorksType': t.data.WorksType
      },
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync("Authorization")
      },
      success: function (res) {
        uploadImgCount++;
        t.data.files.push(JSON.parse(res.data).PayLoad.FilePath);
        t.data.ImagePaths.push(JSON.parse(res.data).PayLoad.FilePath);

        t.setData({
          files: t.data.files,
          ImagePaths: t.data.ImagePaths
        });
        wx.hideToast();
      },
      fail: function (res) {
        wx.hideToast();
        wx.showModal({
          title: '错误提示',
          content: '上传文件失败',
          showCancel: false,
          success: function (res) { }
        })
      }
    });

  }).catch(e => {
    wx.hideToast();
    util.showToast({
      image: 2,
      title: config.catchMsg
    });
  });
}

// 获取 图片数组 和 视频数组 以及合并数组
var getPathArr = t => {
    let imgarr = t.data.upImgArr || [];
    let upVideoArr = t.data.upVideoArr || [];
    let imgPathArr = [];
    let videoPathArr = [];
    imgarr.map(function (v, i) {
        imgPathArr.push(v.path)
    })
    upVideoArr.map(function (v, i) {
        videoPathArr.push(v.tempFilePath)
    })
    let filesPathsArr = imgPathArr.concat(videoPathArr);
    return filesPathsArr;
}

/**
 * upFilesFun(this,object)
 * object:{
 *    url     ************   上传路径 (必传)
 *    filesPathsArr  ******  文件路径数组
 *    name           ******  wx.uploadFile name
 *    formData     ******    其他上传的参数
 *    startIndex     ******  开始上传位置 0
 *    successNumber  ******     成功个数
 *    failNumber     ******     失败个数
 *    completeNumber  ******    完成个数
 * }
 * progress:上传进度
 * success：上传完成之后
 */

var upFilesFun = (t, data, progress, success) =>{
    let _this = t;
    let url = data.url;
    let filesPath = data.filesPathsArr ? data.filesPathsArr : getPathArr(t);
    let name = data.name || 'file';
    let formData = data.formData || {};
    let startIndex = data.startIndex ? data.startIndex : 0;
    let successNumber = data.successNumber ? data.successNumber : 0;
    let failNumber = data.failNumber ? data.failNumber : 0;
    if (filesPath.length == 0) {
      success([]);
      return;
    }
    const uploadTask = wx.uploadFile({
        url: url,
        filePath: filesPath[startIndex],
        name: name,
        formData: formData,
        success: function (res) {
            var data = res.data
            successNumber++;
            // console.log('success', successNumber)
            // console.log('success',res)
            // 把后台返回的地址链接存到一个数组
            let uploaded = t.data.uploadedPathArr || [];
            var da = JSON.parse(res.data);
            // console.log(da)
            if (da.code == 1001) {
                // ### 此处可能需要修改 以获取图片路径
                uploaded.push(da.data)

                t.setData({
                    uploadedPathArr: uploaded
                })
            }
        },
        fail: function(res){
            failNumber++;
            // console.log('fail', filesPath[startIndex])
            // console.log('failstartIndex',startIndex)
            // console.log('fail', failNumber)
            // console.log('fail', res)
        },
        complete: function(res){

            if (startIndex == filesPath.length - 1 ){
                // console.log('completeNumber', startIndex)
                // console.log('over',res)
                let sucPathArr = t.data.uploadedPathArr;
                success(sucPathArr);
                t.setData({
                    uploadedPathArr: []
                })
                console.log('成功：' + successNumber + " 失败：" + failNumber)
            }else{
                startIndex++;
                // console.log(startIndex)
                data.startIndex = startIndex;
                data.successNumber = successNumber;
                data.failNumber = failNumber;
                upFilesFun(t, data, progress, success);
            }
        }
    })

    uploadTask.onProgressUpdate((res) => {
        res['index'] = startIndex;
        // console.log(typeof (progress));
        if (typeof (progress) == 'function') {
            progress(res);
        }
        // console.log('上传进度', res.progress)
        // console.log('已经上传的数据长度', res.totalBytesSent)
        // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })

}
module.exports = { chooseImage, chooseVideo, chooseRecord, upFilesFun, getPathArr}